import axios from 'axios'
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from 'axios'
import type { LoginResponse } from '@/types/auth'

// 定义基础响应类型
interface BaseResponse<T = any> {
  data?: T
  error?: string
  details?: Record<string, string[]>
}

const service: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log('请求拦截器 - 请求配置:', config)
    const token = localStorage.getItem('access_token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    console.log('请求拦截器 - 最终配置:', config)
    return config
  },
  (error) => {
    return Promise.reject({
      message: '请求配置错误',
      original: error,
    })
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 添加调试信息
    console.log('响应拦截器 - 原始响应:', response)
    console.log('响应拦截器 - response.data:', response.data)
    console.log('响应拦截器 - response.status:', response.status)
    console.log('响应拦截器 - response.config.url:', response.config.url)

    // 处理成功响应（2xx）
    if (response.status >= 200 && response.status < 300) {
      // 针对注册接口的特殊处理
      if (response.config.url?.endsWith('/register/')) {
        const result = {
          ...response.data,
          // 确保包含必要字段
          user: response.data?.user || null,
          access: response.data?.access || null,
          refresh: response.data?.refresh || null,
        }
        console.log('注册接口响应处理结果:', result)
        return result
      }
      // 针对登录接口的特殊处理
      if (response.config.url?.endsWith('/login/')) {
        const result = {
          ...response.data,
          user_id: response.data?.user_id,
          username: response.data?.username,
          access: response.data?.access,
          refresh: response.data?.refresh,
        } as LoginResponse
        console.log('登录接口响应处理结果:', result)
        return result
      }
      // 对于地址列表接口，返回默认的地址列表结构
      if (response.config.url?.includes('/auth/addresses/')) {
        console.log('=== 执行地址列表接口处理 ===')
        console.log('原始response.data:', response.data)
        console.log('response.data类型:', typeof response.data)
        console.log('是否是数组:', Array.isArray(response.data))
        const data = response.data || []
        const result = {
          results: data, // ✅ 使用实际数据
          count: data.length, // ✅ 使用实际数量
          next: null,
          previous: null,
        }
        console.log('地址列表接口默认响应:', result)
        return result
      }
      // 确保返回的数据有效
      if (response.data !== undefined && response.data !== null) {
        console.log('返回原始数据:', response.data)
        return response.data
      }
      // 对于其他接口，返回空对象
      const result = {}
      console.log('其他接口默认响应:', result)
      return result
    }

    // 非2xx状态码但进入这里的情况（如304）
    return Promise.reject({
      message: `非预期状态码: ${response.status}`,
      response,
    })
  },
  (error) => {
    // 处理网络错误和4xx/5xx响应
    if (error.response) {
      // DRF错误格式处理
      const { data, status } = error.response

      if (status === 400) {
        // 详细字段错误处理
        const details = typeof data === 'object' ? data : {}
        const message = data.detail || '请求参数错误'

        return Promise.reject({
          message,
          details,
          status,
          isValidationError: true,
        })
      }

      return Promise.reject({
        message: data.detail || `请求失败 (${status})`,
        status,
        original: error,
      })
    } else if (error.request) {
      return Promise.reject({
        message: '网络错误，请检查连接',
        isNetworkError: true,
      })
    }

    return Promise.reject({
      message: '未知错误',
      original: error,
    })
  },
)

// 封装类型安全的请求方法
export const request = {
  get: <T>(url: string, config?: AxiosRequestConfig) =>
    service.get<T, AxiosResponse<T>>(url, config),
  post: <T>(url: string, data?: any, config?: AxiosRequestConfig) =>
    service.post<T, AxiosResponse<T>>(url, data, config),
  put: <T>(url: string, data?: any, config?: AxiosRequestConfig) =>
    service.put<T, AxiosResponse<T>>(url, data, config),
  delete: <T>(url: string, config?: AxiosRequestConfig) =>
    service.delete<T, AxiosResponse<T>>(url, config),
  patch: <T>(url: string, data?: any, config?: AxiosRequestConfig) =>
    service.patch<T, AxiosResponse<T>>(url, data, config),
}

export default service
